package com.bootdo.coach.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bootdo.coach.domain.TabDeviceType;
import com.bootdo.coach.domain.TabMsg;
import com.bootdo.coach.domain.TabUser;
import com.bootdo.coach.domain.TabUserMsg;
import com.bootdo.coach.service.TabDeviceTypeService;
import com.bootdo.coach.service.TabMsgService;
import com.bootdo.coach.service.TabUserMsgService;
import com.bootdo.coach.service.TabUserService;
import com.bootdo.coach.vo.TabMsgVo;
import com.bootdo.common.annotation.Log;
import com.bootdo.common.controller.BaseController;
import com.bootdo.common.utils.PageUtils;
import com.bootdo.common.utils.Query;
import com.bootdo.common.utils.R;
import com.bootdo.common.utils.StringUtils;

import io.swagger.annotations.ApiOperation;

@RequestMapping("/msg/msg")
@Controller
public class MsgController extends BaseController{
	private String prefix = "msg/msg";
	
	@Autowired
	private TabUserService userService;
	
	@Autowired
	private TabUserMsgService userMsgService;

	@Autowired
	private TabDeviceTypeService deviceTypeService;
	
	@Autowired
	private TabMsgService msgService;
	
	@RequiresPermissions("msg:msg:list")
	@GetMapping("msg")
	String list(Model model) {
		return prefix + "/list";
	}
	
	@ApiOperation(value="获取消息列表", notes="")
	@ResponseBody
	@GetMapping("/dataList")
	@RequiresPermissions("msg:msg:list")
	public PageUtils list(@RequestParam Map<String, Object> params) {
		// 查询列表数据
        Query query = new Query( params );
		List<TabMsgVo> list = msgService.list(query);
		int total = msgService.count(query);
		PageUtils pageUtil = new PageUtils(list, total);
		return pageUtil;
	}
	
	private List<TabDeviceType> getAllDeviceType() {
		List<TabDeviceType> deviceTypes = deviceTypeService.list(new HashMap<String, Object>());
		if (deviceTypes == null) {
			deviceTypes = new ArrayList<TabDeviceType>();
		}
		TabDeviceType one = new TabDeviceType();
		one.setId(0l);
		one.setDeviceTypeName("全部");
		deviceTypes.add(0, one);
		return deviceTypes;
	}

	@RequiresPermissions("msg:msg:sendMsg")
	@Log("添加消息")
	@GetMapping("/sendMsg")
	String sendMsg(Model model) {
		model.addAttribute("deviceTypes", getAllDeviceType());
		return prefix + "/add";
	}

	@RequiresPermissions("msg:msg:updateMsg")
	@Log("编辑消息")
	@GetMapping("/updateMsg/{id}")
	String updateMsg(Model model, @PathVariable("id") Long id) {
		model.addAttribute("deviceTypes", getAllDeviceType());
		TabMsgVo msg = msgService.selectByMsgId(id);
		model.addAttribute("msg", msg);
		return prefix+"/edit";
	}
	
	@RequiresPermissions("msg:msg:checkMsg")
	@Log("审核消息")
	@GetMapping("/checkMsg/{id}")
	String checkMsg(Model model, @PathVariable("id") Long id) {
		model.addAttribute("deviceTypes", getAllDeviceType());
		TabMsgVo msg = msgService.selectByMsgId(id);
		if (msg.getSendType() == 1 && msg.getDeviceTypeId() == 0l) {
			msg.setDeviceTypeName("全部产品");
		}
		model.addAttribute("msg", msg);
		return prefix+"/check";
	}

	@RequiresPermissions("msg:msg:sendMsg")
	@Log("保存消息")
	@PostMapping("/saveMsg")
	@ResponseBody
	R saveMsg(TabMsgVo record) {
//		if (record.getSendType() == 0) {
//			if (StringUtils.isEmpty(record.getAccount())) {
//				return R.error("请填写存在的用户账号");
//			}
//
//			List<TabUser> list = userService.selectByAccount(record.getAccount());
//			if (list == null || list.isEmpty()) {
//				return R.error("请填写存在的用户账号");
//			}
//			record.setUserId(list.get(0).getId());
//		}else {
//			record.setUserId(0l);
//		}
		
		TabMsg msg = new TabMsg();
		msg.setTitle(record.getTitle());
		msg.setContent(record.getContent());
		msg.setUserId(record.getUserId());
		msg.setCreateTime(new Date());
		msg.setStatus(0);
		msg.setSendType(-1);
		msg.setDeviceTypeId(-1l);
		
		if (msgService.insertSelective(msg) > 0) {
			return R.ok();
		}
		return R.error();
	}

	@RequiresPermissions("msg:msg:updateMsg")
	@Log("更新消息")
	@PostMapping("/update")
	@ResponseBody
	R update(TabMsgVo record) {
//		if (record.getSendType() == 0) {
//			if (StringUtils.isEmpty(record.getAccount())) {
//				return R.error("请填写存在的用户账号");
//			}
//
//			List<TabUser> list = userService.selectByAccount(record.getAccount());
//			if (list == null || list.isEmpty()) {
//				return R.error("请填写存在的用户账号");
//			}
//			record.setUserId(list.get(0).getId());
//		}else {
//			record.setUserId(0l);
//		}

		TabMsg msg = new TabMsg();
		msg.setId(record.getId());
		msg.setTitle(record.getTitle());
		msg.setContent(record.getContent());
		msg.setDeviceTypeId(record.getDeviceTypeId());
		msg.setUserId(record.getUserId());
		msg.setCreateTime(new Date());
		msg.setStatus(0);
		msg.setSendType(record.getSendType());
		
		if (msgService.updateByPrimaryKeySelective(msg) > 0) {
			return R.ok();
		}
		return R.error();
	}
	
	@RequiresPermissions("msg:msg:checkMsg")
	@Log("审核消息")
	@PostMapping("/check")
	@ResponseBody
	R check(TabMsgVo record) {
		if (record.getSendType() == 0) {
			if (StringUtils.isEmpty(record.getAccount())) {
				return R.error("请填写存在的用户账号");
			}

			List<TabUser> list = userService.selectByAccount(record.getAccount());
			if (list == null || list.isEmpty()) {
				return R.error("请填写存在的用户账号");
			}
			record.setUserId(list.get(0).getId());
		}else {
			record.setUserId(0l);
		}
		
		TabMsg msg = msgService.selectByPrimaryKey(record.getId());
		msg.setStatus(record.getStatus());
		
		msg.setSendType(record.getSendType());
		msg.setDeviceTypeId(record.getDeviceTypeId());
		
		if (msgService.updateByPrimaryKeySelective(msg) > 0) {
			if (msg.getStatus() == 1) {
				// 插入用户消息
				List<Long> userIdList = null;
				if (msg.getSendType() == 1l) {
					userIdList = userService.findUserIdList(msg.getDeviceTypeId());
				}else {
					userIdList = new ArrayList<Long>();
					userIdList.add(msg.getUserId());
				}
				if (userIdList != null && !userIdList.isEmpty()) {
					TabUserMsg tabUserMsg = null;
					for (Long userId : userIdList) {
						tabUserMsg = new TabUserMsg();
						tabUserMsg.setMsgId(record.getId());
						tabUserMsg.setUserId(userId);
						userMsgService.insert(tabUserMsg);
					}
				}
			}
			
			return R.ok();
		}
		return R.error();
	}

	@RequiresPermissions("msg:msg:deleteMsg")
	@Log("删除消息")
	@PostMapping("/deleteMsg")
	@ResponseBody
	R deleteMsg(Long id) {
		if (msgService.deleteByPrimaryKey(id) > 0) {
			// 删除用户消息
			userMsgService.deleteUserMsgByMsgId(id);
			
			return R.ok();
		}
		return R.error();
	}
}
